/*
 * Copyright (C) 2011 Imavis Srl
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.imavis.video.parse.h264;

import com.imavis.video.parse.impl.BitBuffer;
import java.nio.ByteBuffer;

/**
 *
 * @author Andrea Gualano
 */
class H264Utils {
    private static final int START_CODE_PREFIX = 0x00000001;

    public static boolean seekStartCodePrefix(final ByteBuffer bb) {
        int state = 0xFFFFFFFF;
        while (bb.hasRemaining()) {
            state = (state << 8) | (bb.get() & 0xFF);
            if (state == START_CODE_PREFIX) {
                return true;
            }
        }
        return false;
    }

    public static int getNalUnitType(final ByteBuffer bb) {
        return bb.get() & 0x1F;
    }

    public static void skipExpGolomb(final BitBuffer bb) {
        getExpGolombUnsigned(bb);
    }

    public static int getExpGolombUnsigned(final BitBuffer bb) {
        int leadingZeroBits = 0;
        while (!bb.getBit()) {
            leadingZeroBits++;
        }
        final int suffix = bb.getBits(leadingZeroBits);
        final int minimum = (1 << leadingZeroBits) - 1;
        return minimum + suffix;
    }

    public static int getExpGolombSigned(final BitBuffer bb) {
        final int ue = getExpGolombUnsigned(bb);
        final int sign = (ue % 2 == 0) ? -1 : 1;
        final int magn = (ue + 1) / 2;
        return sign * magn;
    }

    private H264Utils() {
    }
}
